package gw.demo2.service;

import gw.demo2.entity.PurchaseRecord;
import gw.demo2.entity.User;
import gw.demo2.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import gw.demo2.mapper.PurchaseRecordMapper;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PurchaseRecordMapper purchaseRecordMapper;

    public User login(int userId, String password) {
        User user = userMapper.selectUserById(userId);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }

    public boolean register(String nickname, String password) {
        if (userMapper.selectUserByNickname(nickname) != null) {
            return false;
        }
        User user = new User();
        user.setNickname(nickname);
        user.setPassword(password);
        return userMapper.insertUser(user) > 0;
    }

    public int getUserIdByNickname(String nickname) {
        return userMapper.selectUserByNickname(nickname).getUserId();
    }

    public boolean updateUser(int userId, String newNickname, String newPassword) {
        User user = new User();
        user.setUserId(userId);
        user.setNickname(newNickname);
        user.setPassword(newPassword);
        return userMapper.updateUser(user) > 0;
    }

    public List<PurchaseRecord> getPurchaseRecordsByUserId(int userId) {
        return purchaseRecordMapper.selectPurchaseRecordsByUserId(userId);
    }
}